package com.et.machine.manager.vm.login

import android.content.Context
import android.os.Bundle
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.view.inputmethod.InputMethodManager
import android.widget.Toast
import androidx.fragment.app.Fragment
import androidx.lifecycle.ViewModelProvider
import androidx.navigation.Navigation
import com.et.drive.info.IMachineSignInfoImpl
import com.et.machine.convert.IMachineSignInfo
import com.et.machine.convert.machineInfo
import com.et.machine.databinding.FragmentLoginBinding

class LoginFragment : Fragment() {

    companion object {
        fun newInstance() = LoginFragment()
    }

    private lateinit var viewModel: LoginViewModel
    private lateinit var binding: FragmentLoginBinding

    override fun onCreateView(
        inflater: LayoutInflater, container: ViewGroup?,
        savedInstanceState: Bundle?
    ): View = FragmentLoginBinding.inflate(inflater).apply {
        binding = this
    }.root

    override fun onActivityCreated(savedInstanceState: Bundle?) {
        super.onActivityCreated(savedInstanceState)
        viewModel = ViewModelProvider(this).get(LoginViewModel::class.java)
        binding.login.setOnClickListener { button->
            if (binding.userName.text.toString() == "manager" && binding.password.text.toString() == "314159") {
                val manager: InputMethodManager =
                    requireContext().getSystemService(Context.INPUT_METHOD_SERVICE) as InputMethodManager
                manager.hideSoftInputFromWindow(button.windowToken, InputMethodManager.HIDE_NOT_ALWAYS)
                if (machineInfo == null){
                    binding.progress.visibility = View.VISIBLE
                    IMachineSignInfoImpl.observer {
                        Navigation.findNavController(button)
                            .navigate(LoginFragmentDirections.actionLoginFragmentToHomeFragment())
                    }
                }else{
                    binding.progress.visibility = View.GONE
                    Navigation.findNavController(button)
                        .navigate(LoginFragmentDirections.actionLoginFragmentToHomeFragment())
                }
            } else {
                Toast.makeText(requireContext(), "用户名或密码错误", Toast.LENGTH_LONG).show()
            }
        }

    }

}